<template>
  <div class="search">
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="handleSearch">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-item label="任务名称" prop="name" >
                <a-input
                  type="text" allowClear
                  v-model="searchForm.name"
                  placeholder="请输入"
                />
              </a-form-item>
            </a-col>
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="12" >
                <a-button type="primary"  style="left: 10px" @click="handleSearch" icon="search">查询</a-button>
                <a-button type="primary"  @click="handleReset" icon="reload" style="margin-left: 8px;left: 10px">重置</a-button>
            </a-col>
          </span>
          </a-row>
        </a-form>
      </div>
      <!--<a-row class="operation">
        <a-button @click="passAll" icon="md-checkmark-circle-outline">批量通过</a-button>
        <a-button @click="backAll" icon="md-close">批量驳回</a-button>
        <a-button @click="getDataList" icon="md-refresh">刷新</a-button>
      </a-row>-->
      <a-row>
        <a-table
          bordered
          :loading="loading"
          rowKey="id"
          :scroll="{x:true}"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          @change="handleTableChange"
          ref="table"
        >
          <template slot="action" slot-scope="t,r">
            <span v-if="!Boolean(r.isSuspended)">
              <a href="javascript:void(0);" @click="detail(r)">查看并处理</a>
            </span>
            <a-divider type="vertical" />
            <a-dropdown :trigger="['hover']">
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                ...
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="0" v-if="!Boolean(r.isSuspended)">
                  <span>
                    <a href="javascript:void(0);" @click="delegateTask(r)">委托他人代办</a>
                  </span>
                </a-menu-item>
                <a-menu-item key="1">
                  <span>
                    <a href="javascript:void(0);" @click="history(r)">历史</a>
                  </span>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </a-table>
      </a-row>
    </a-card>
    <!---->
    <a-modal title="审批历史" v-model="modalLsVisible" :mask-closable="false" :width="'80%'" :footer="null">
      <div v-if="modalLsVisible">
        <component :is="historicDetail" :title="title" :procInstId="procInstId"></component>
      </div>
    </a-modal>
    <!--流程表单-->
    <a-modal :title="lcModa.title" v-model="lcModa.visible" :footer="null" :maskClosable="false" width="90%">
      <component :disabled="lcModa.disabled"
                 v-if="lcModa.visible"
                 :is="lcModa.formComponent"
                 :processData="lcModa.processData"
                 :isNew = "lcModa.isNew"
                 :task="true"
                 @passTask = "()=>passTask(lcModa.processData)"
                 @backTask = "()=>backTask(lcModa.processData)"
                 @close="lcModa.visible=false,lcModa.disabled = false">
      </component>
    </a-modal>
    <!-- 审批操作 -->
    <a-modal :title="modalTaskTitle" v-model="modalTaskVisible" :mask-closable="false" :width="500">
      <div v-if="modalTaskVisible">
        <a-form ref="form" :model="form" :label-width="85" :rules="formValidate">
          <a-form-item label="审批意见" prop="reason">
            <a-input type="textarea" v-model="form.comment" :rows="4" />
          </a-form-item>
          <a-form-item label="下一审批人" prop="assignees" v-show="showAssign" :error="error">
            <a-select
              v-model="form.assignees"
              placeholder="请选择"
              allowClear
              mode="multiple"
              :loading="userLoading"
            >
              <a-select-option v-for="(item, i) in assigneeList" :key="i" :value="item.username">{{item.realname}}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="下一审批人" v-show="isGateway">
            <span>分支网关处暂不支持自定义选择下一审批人，将发送给下一节点所有人</span>
          </a-form-item>
          <div v-show="form.type==1">
            <a-form-item label="驳回至">
              <a-select
                v-model="form.backTaskKey"
                :loading="backLoading"
                @change="changeBackTask"
              >
                <a-select-option v-for="(item, i) in backList" :key="i" :value="item.key">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="指定原节点审批人" prop="assignees" v-show="form.backTaskKey!=-1" :error="error">
              <a-select
                v-model="form.assignees"
                placeholder="请选择"
                allowClear
                mode="multiple"
                :loading="userLoading"
              >
                <a-select-option v-for="(item, i) in assigneeList" :key="i" :value="item.username">{{item.realname}}</a-select-option>
              </a-select>
            </a-form-item>
          </div>
          <a-form-item label="选择委托人" prop="userId" :error="error" v-show="form.type==2">
            <JSelectUserByDep v-model="form.userId" :multi="false"></JSelectUserByDep>
          </a-form-item>
          <a-form-item label="消息通知">
            <a-checkbox v-model="form.sendMessage">站内消息通知</a-checkbox>
            <a-checkbox v-model="form.sendSms" disabled>短信通知</a-checkbox>
            <a-checkbox v-model="form.sendEmail" disabled>邮件通知</a-checkbox>
          </a-form-item>
        </a-form>
      </div>
      <div slot="footer">
        <a-button type="text" @click="modalTaskVisible=false">取消</a-button>
        <a-button type="primary" :loading="submitLoading" @click="handelSubmit">提交</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { activitiMixin } from '@/views/activiti/mixins/activitiMixin'
import { postAction, getAction } from '@/api/manage'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'

export default {
  name: "todo-manage",
  mixins:[activitiMixin,JeecgListMixin],
  components:{JSelectUserByDep},
  data() {
    return {
      openSearch: true,
      openTip: true,
      loading: true, // 表单加载状态
      modalTaskVisible: false,
      userLoading: false,
      backLoading: false,
      selectCount: 0, // 多选计数
      selectList: [], // 多选数据
      assigneeList: [],
      backList: [
        {
          key: "-1",
          name: "发起人"
        }
      ],
      error: "",
      showAssign: false,
      searchForm: {
        // 搜索框对应data对象
        name: "",
        pageNumber: 1,
        pageSize: 10
      },
      modalTaskTitle: "",
      modalTitle: "", // 添加或编辑标题
      form: {
        id: "",
        userId: "",
        procInstId: "",
        comment: "",
        type: 0,
        assignees: [],
        backTaskKey: "-1",
        sendMessage: true,
        sendSms: false,
        sendEmail: false
      },
      formValidate: {
        // 表单验证规则
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'任务名称',
          align:"center",
          dataIndex: 'title',
          width: 120,
          scopedSlots: { customRender: 'title' },
        },
        {
          title:'订单号',
          align:"center",
          dataIndex: 'orderNo',
          scopedSlots: { customRender: 'orderNo' },
        },
        {
          title:'金额',
          align:"center",
          dataIndex: 'purchasePrice',
          scopedSlots: { customRender: 'purchasePrice' },
        },
        {
          title:'所属流程',
          align:"center",
          width: 120,
          dataIndex: 'processName',
          scopedSlots: { customRender: 'processName' },
        },
        {
          title:'委托人',
          align:"center",
          dataIndex: 'owner',
          width: 100,
          scopedSlots: { customRender: 'owner' },
        },
        {
          title:'流程发起人',
          align:"center",
          dataIndex: 'applyer',
          width: 110,
          scopedSlots: { customRender: 'applyer' },
        },
        {
          title:'优先级',
          align:"center",
          dataIndex: 'priority',
          scopedSlots: { customRender: 'priority' },
          customRender:function (text) {
            if(text === 0){
              return <a-tag color="green"> 普通 </a-tag>
            } else if(text === 1) {
              return <a-tag color="orange"> 重要 </a-tag>
            } else if(text === 2) {
              return <a-tag color="red"> 紧急 </a-tag>
            } else {
              return <a-tag color="#999"> 无 </a-tag>
            }
          }
        },
        {
          title:'状态',
          align:"center",
          dataIndex: 'isSuspended',
          scopedSlots: { customRender: 'isSuspended' },
          customRender:function (text) {
            if(!Boolean(text)){
              return <a-tag v-if="" color="green"> 已激活 </a-tag>
            } else {
              return <a-tag v-if="Boolean(t)" color="orange"> 已挂起 </a-tag>
            }
          }
        },
        {
          title:'创建时间',
          align:"center",
          dataIndex: 'createTime',
          width: 180,
          scopedSlots: { customRender: 'createTime' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
            fixed: "right",
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      submitLoading: false, // 添加或编辑提交状态
      dataSource: [], // 表单数据
      ipagination: {},
      dictPriority: [],
      isGateway: false,
      title: '',
      lcModa: {
        title:'',
        disabled:false,
        visible:false,
        formComponent : null,
        isNew : false
      },
      url:{
        getById: '/actBusiness/getById',
        list:'/act/todoList',
        pass:'/act/pass',
        back:'/act/back',
        backToTask:'/actTask/backToTask',
        delegate:'/actTask/delegate',
        getNextNode:'/activiti_process/getNextNode',
        getNode:'/activiti_process/getNode/',
        getBackList:'/actTask/getBackList/',
        passAll:'/actTask/passAll/',
        backAll:'/actTask/backAll/',
      },
      /*历史*/
      modalLsVisible: false,
      procInstId:'',
    };
  },
  watch: {
    '$route.query.id': {
      deep: true,
      immediate: true,
      handler() {
        if(this.$route.query.id !== null) {
          let busId = this.$route.query.id;
          if(busId != null) {
            this.$router.push({ query: {} })
            this.init(busId);
          }

        }
      }
    }
  },
  methods: {
    init(busId) {
      getAction(this.url.getById, {
        id: busId
      }).then(res => {
        if(res.success) {
          this.detail(res.result);
        }
      })
    },
    loadData() {
      this.loading = true;
      getAction(this.url.list, this.searchForm).then(res => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.ipagination.total = res.result.total;
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination;
      this.searchForm.pageNumber = pagination.current;
      this.searchForm.pageSize = pagination.pageSize;
      this.loadData();
    },
    handleSearch() {
      this.loadData();
    },
    handleReset() {
      this.searchForm={};
      // 重新加载数据
      this.loadData();
    },
    showSelect(e) {
      this.selectList = e;
      this.selectCount = e.length;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    /*审批提交的方法*/
    handelSubmit() {
      this.submitLoading = true;
      let formData = Object.assign({},this.form);
      formData.assignees = formData.assignees.join(",");
      if (formData.type == 0) {
        // 通过
        if (this.showAssign && formData.assignees.length < 1) {
          this.$message.error("请至少选择一个审批人")
          this.submitLoading = false;
          return;
        } else {
          this.error = "";
        }
        postAction(this.url.pass,formData).then(res => {
          if (res.success) {
            this.lcModa.visible=false
            this.$message.success("操作成功");
            this.modalTaskVisible = false;
            this.loadData();
          } else {
            this.$message.error(res.message)
          }
        }).finally(() => {
          this.submitLoading = false;
        });
      } else if (formData.type == 1) {
        // 驳回
        if (formData.backTaskKey == "-1") {
          // 驳回至发起人
          postAction(this.url.back,formData).then(res => {
            this.submitLoading = false;
            if (res.success) {
              this.lcModa.visible=false
              this.$message.success("操作成功");
              this.modalTaskVisible = false;
              this.loadData();
            }
          });
        } else {
          // 自定义驳回
          if (formData.backTaskKey != "-1" && formData.assignees.length < 1) {
            this.$message.error("请至少选择一个审批人")
            this.submitLoading = false;
            return;
          } else {
            this.error = "";
          }
          postAction(this.url.backToTask, formData).then(res => {
            if(res.success) {
              this.lcModa.visible=false
              this.$message.success("操作成功");
              this.modalTaskVisible = false;
              this.loadData();
            }
          }).finally(() => {
            this.submitLoading = false;
          });
        }
      } else if (formData.type == 2) {
        // 委托
        if (!formData.userId) {
          this.$message.error("请选择一委托人")
          this.submitLoading = false;
          return;
        } else {
          this.error = "";
        }
        postAction(this.url.delegate,formData).then(res => {
          if (res.success) {
            this.$message.success("操作成功");
            this.modalTaskVisible = false;
            this.loadData();
          }
        }).finally(() => {
          this.submitLoading = false;
        });
      }
    },
    detail(r) {
      this.lcModa.disabled = true;
      this.lcModa.title = '查看流程业务信息：'+r.processName;
      this.lcModa.formComponent = this.getFormComponent(r.routeName).component;
      this.lcModa.processData = r;
      this.lcModa.isNew = false;
      this.lcModa.visible = true;
    },
    passTask(v) {
      this.modalTaskTitle = "审批通过";
      this.form.id = v.id;
      this.form.procInstId = v.procInstId;
      this.form.priority = v.priority;
      this.form.type = 0;
      this.modalTaskVisible = true;
      this.userLoading = true;
      getAction(this.url.getNextNode,{
        procDefId:v.procDefId,
        currActId:v.key
      }).then(res => {
        this.userLoading = false;
        if (res.success) {
          if (res.result.type == 4) {
            this.isGateway = true;
            this.showAssign = false;
            this.error = "";
            return;
          }
          this.isGateway = false;
          if (res.result.users && res.result.users.length > 0) {
            this.error = "";
            this.assigneeList = res.result.users;
            // 默认勾选
            let ids = [];
            res.result.users.forEach(e => {
              ids.push(e.username);
            });
            this.form.assignees = ids;
            this.showAssign = true;
          } else {
            this.form.assignees = [];
            this.showAssign = false;
          }
        }
      });
    },
    changeBackTask(v) {
      if (v == "-1") {
        return;
      }
      this.userLoading = true;
      getAction(this.url.getNode+v).then(res => {
        this.userLoading = false;
        if (res.success) {
          if (res.result.users && res.result.users.length > 0) {
            this.assigneeList = res.result.users;
            // 默认勾选
            let ids = [];
            res.result.users.forEach(e => {
              ids.push(e.username);
            });
            this.form.assignees = ids;
          }
        }
      });
    },
    backTask(v) {
      this.modalTaskTitle = "审批驳回";
      this.form.id = v.id;
      this.form.procInstId = v.procInstId;
      this.form.procDefId = v.procDefId;
      this.form.priority = v.priority;
      this.form.type = 1;
      this.showAssign = false;
      this.modalTaskVisible = true;
      // 获取可驳回节点
      this.backList = [
        {
          key: "-1",
          name: "发起人"
        }
      ];
      this.form.backTaskKey = "-1";
      this.backLoading = true;
      getAction(this.url.getBackList+v.procInstId).then(res => {
        this.backLoading = false;
        if (res.success) {
          res.result.forEach(e => {
            this.backList.push(e);
          });
        }
      });
    },
    delegateTask(v) {
      this.modalTaskTitle = "委托他人代办";
      this.form.id = v.id;
      this.form.procInstId = v.procInstId;
      this.form.type = 2;
      this.showAssign = false;
      this.modalTaskVisible = true;
    },
    history(v) {
      if (!v.procInstId) {
        this.$message.error("流程实例ID不存在");
        return;
      }
      this.title = "审批历史"
      this.procInstId = v.procInstId;
      this.modalLsVisible = true;
    },
    passAll() {
      if (this.selectCount <= 0) {
        this.$message.warning("您还未选择要通过的数据");
        return;
      }
      // 批量通过
      this.modalVisible = true;
      this.$confirm({
        title: "确认通过",
        content:
          "您确认要通过所选的 " +
          this.selectCount +
          " 条数据? 注意：将默认分配给节点设定的所有可审批用户",
        loading: true,
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function(e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          postAction(this.url.passAll,{
            ids: ids
          }).then(res => {
            if (res.success) {
              this.$message.success("操作成功");
              this.modalVisible = false;
              this.clearSelectAll();
              this.loadData();
            }
          });
        }
      });
    },
    backAll() {
      if (this.selectCount <= 0) {
        this.$message.warning("您还未选择要驳回的数据");
        return;
      }
      // 批量驳回
      this.modalVisible = true;
      this.$confirm({
        title: "确认驳回",
        content:
          "您确认要驳回所选的 " +
          this.selectCount +
          " 条数据? 注意：所有流程将驳回至发起人",
        loading: true,
        onOk: () => {
          let procInstIds = "";
          this.selectList.forEach(function(e) {
            procInstIds += e.procInstId + ",";
          });
          procInstIds = procInstIds.substring(0, procInstIds.length - 1);
          postAction(this.url.backAll,{procInstIds:procInstIds}).then(res => {
            if (res.success) {
              this.$message.success("操作成功");
              this.modalVisible = false;
              this.clearSelectAll();
              this.loadData();
            }
          });
        }
      });
    },
  },
};
</script>
<style></style>